<template>
  <div>
    <div class="coordinate-container">
      <div class="map-section">
        <input
          v-model="keywords"
          type="text"
          placeholder="请输入关键词"
          @input="onInput"
          style="width: 400px; padding: 5px; margin-right: 5px;"
        />
        <ul class="options" v-if="options.length > 0">
          <li class="option"
            v-for="item in options"
            :key="item.id"
            @click="selectOption(item)"
          >
            <span>{{ item.name }}</span>
            <span>{{ item.district }}</span>
          </li>
        </ul>
        <div id="coordinate-map" class="map-container"></div>
      </div>
      <div class="info-box">
        纬度：{{ form.lat }}
        <br />
        经度：{{ form.lng }}
        <p>详细地址：{{ form.address }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "Coordinate",
  data() {
    return {
      map: null,
      marker: null,
      geoCoder: null,
      AutoComplete: null,
      keywords: "",
      form: {
        lng: "",
        lat: "",
        address: "",
        adcode: "",
      },
      options: [],
    };
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
      })
        .then((AMap) => {
          this.map = new AMap.Map("coordinate-map", {
            viewMode: "2D",
            zoom: 5,
            center: [105.602725, 37.076636],
          });
          this.geoCoder = new AMap.Geocoder({ city: "010", radius: 1000 });
          this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
          this.map.on("click", (e) => {
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            this.removeMarker();
            this.setMapMarker();
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },

    setMapMarker() {
      if (!this.map || !this.form.lng || !this.form.lat) return;

      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);
    },

    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null;
      }
    },

    toGeoCoder() {
      const lnglat = [this.form.lng, this.form.lat];
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress;
        }
      });
    },

    onInput() {
      if (this.keywords !== "") {
        this.AutoComplete.search(this.keywords, (status, result) => {
          if (status === "complete" && result.tips) {
            this.options = result.tips;
          } else {
            this.options = [];
          }
        });
      } else {
        this.options = [];
      }
    },

    selectOption(val) {
      if (!val || !val.location) return;
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: `${val.district} ${val.address}`,
        adcode: val.adcode,
      };
      this.options = [];
      this.removeMarker();
      this.setMapMarker();
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>

<style>
.coordinate-container {
  display: flex;
}

.map-section {
  flex: 1;
}

.map-container {
  width: 500px;
  height: 300px;
}

.info-box {
  margin-left: 20px;
}

.options {
  list-style-type: none;
  padding: 0;
  margin: 0;
  border: 1px solid #ccc;
  max-height: 150px;
  overflow-y: auto;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.option {
  padding: 5px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option:hover {
  background-color: #f5f5f5;
}
</style>
